/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package xin.alum.aim.server;

import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import lombok.experimental.UtilityClass;
import xin.alum.aim.AIM;
import xin.alum.aim.coder.*;
import xin.alum.aim.config.AimProperties;
import xin.alum.aim.config.DataAgreement;
import xin.alum.aim.constant.AIMConstant;
import xin.alum.aim.constant.ChannelAttr;
import xin.alum.aim.model.proto.Packet;
import xin.alum.aim.socks.SocksServerHandler;
import xin.alum.aim.util.ApplicationContextUtil;

@UtilityClass
public class ServerInitializer {
    /**
     * 初始化Socekt通道编码
     *
     * @param pipeline
     */
    public void InitAgreement(ChannelPipeline pipeline, Packet.Agreement agreement) {
        if (agreement == null) {
            agreement = ApplicationContextUtil.getBean(AimProperties.class).getAgreement();
        }
        switch (agreement) {
            case Json:
                pipeline.addLast(new JsonDecoder());
                break;
            case Text:
                pipeline.addLast(new DelimiterBasedFrameDecoder(AIMConstant.TEXT_FRAME_MAX_LENGTH, Delimiters.lineDelimiter()));
                pipeline.addLast(new TEXTDecoder());
                break;
            case Binary:
            case ProtoBuf:
                pipeline.addLast(new LengthDecoder());
                pipeline.addLast(new ProtoDecoder());
                break;
            case Tlv:
                pipeline.addLast(new TagDecoder());
                pipeline.addLast(new LengthDecoder());
                pipeline.addLast(new ProtoDecoder());
                break;
            default:
                System.err.println("未知协议类型");
                break;
        }
        pipeline.channel().attr(ChannelAttr.AGREEMENT).set(agreement);
    }
}
